local dunie = fk.CreateSkill{
  name = "hanqing__dunie",
  tags = { Skill.Compulsory },
}

Fk:loadTranslationTable{
  ["hanqing__dunie"] = "蠹啮",
  [":hanqing__dunie"] = "锁定技，结束阶段，你重铸一名角色装备区至多X张牌，然后若重铸了《戒律》，你失去1点体力并将手牌数调整至X"..
  "（X为场上<a href=':hanqing__precept'>《戒律》</a>数）。",

  ["#hanqing__dunie-choose"] = "蠹啮：重铸一名角色装备区至多%arg张牌",
  ["#hanqing__dunie-recast"] = "蠹啮：重铸 %dest 装备区至多%arg张牌，若重铸《戒律》，你失去体力并调整手牌",
}

dunie:addEffect(fk.EventPhaseStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(dunie.name) and player.phase == Player.Finish and
      table.find(player.room.alive_players, function (p)
        return table.find(p:getCardIds("e"), function (id)
          return Fk:getCardById(id).trueName == "precept"
        end) ~= nil
      end)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    local targets, n = {}, 0
    for _, p in ipairs(room.alive_players) do
      if #p:getCardIds("e") > 0 then
        table.insert(targets, p)
        for _, id in ipairs(p:getCardIds("e")) do
          if Fk:getCardById(id).trueName == "precept" then
            n = n + 1
          end
        end
      end
    end
    local to = room:askToChoosePlayers(player, {
      min_num = 1,
      max_num = 1,
      targets = targets,
      skill_name = dunie.name,
      prompt = "#hanqing__dunie-choose:::"..n,
      cancelable = false,
    })[1]
    local cards = room:askToChooseCards(player, {
      target = to,
      min = 1,
      max = n,
      flag = "e",
      skill_name = dunie.name,
      prompt = "#hanqing__dunie-recast::"..to.id..":"..n,
    })
    local yes = table.find(cards, function (id)
      return Fk:getCardById(id).trueName == "precept"
    end)
    room:recastCard(cards, to, dunie.name)
    if yes and not player.dead then
      room:loseHp(player, 1, dunie.name)
      if not player.dead then
        n = 0
        for _, p in ipairs(room.alive_players) do
          for _, id in ipairs(p:getCardIds("e")) do
            if Fk:getCardById(id).trueName == "precept" then
              n = n + 1
            end
          end
        end
        n = player:getHandcardNum() - n
        if n > 0 then
          room:askToDiscard(player, {
            min_num = n,
            max_num = n,
            include_equip = false,
            skill_name = dunie.name,
            cancelable = false,
          })
        elseif n < 0 then
          player:drawCards(-n, dunie.name)
        end
      end
    end
  end,
})

return dunie
